import { _list } from '../../common/api/learn'
import { loading, toast } from '../../utils/util'
const app = getApp()
Page({
  data: {
    type: null,
    pageIndex: 1,
    pageSize: 10,
    name: '',
    list: [],
    finished: false,
    totalCount: null
  },
  getList () {
    loading('加载中')
    _list(
      this.data.name,
      this.data.type,
      this.data.pageIndex,
      this.data.pageSize
    ).then(res => {
      wx.hideLoading()
      if (res.data.IsSuccess) {
        let list = res.data.Data.Data
        let totalCount = res.data.Data.Count
        let finished = list.length >= totalCount
        this.setData({
          list,
          totalCount,
          finished
        })
      } else {
        wx.showModal({
          title: '对不起',
          content: '请求失败，请稍后再试',
          showCancel: false
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.log(err)
      wx.showModal({
        title: '对不起',
        content: err || '网络错误，请稍后再试',
        showCancel: false
      })
    })
  },
  concatList () {
    _list(
      this.data.name,
      this.data.type,
      this.data.pageIndex,
      this.data.pageSize
    ).then(res => {
      this.data.list = this.data.list.concat(res.data.Data.Data)
      this.setData({
        list: this.data.list
      })
    }).catch(err => {
      console.log(err)
      wx.showModal({
        title: '对不起',
        content: err || '网络错误，请稍后再试',
        showCancel: false
      })
    })
  },
  onReachLower() {
    if (this.data.finished) {
      return
    }
    let list = this.data.list
    let totalCount = this.data.totalCount
    if (list.length >= totalCount) {
      this.data.finished = true
      this.setData({
        finished: this.data.finished
      })
    } else {
      this.data.pageIndex += 1
      this.concatList()
    }
  },
  inputHandler (e) {
    let val = e.detail
    this.data.name = val
  },
  search () {
    this.data.pageIndex = 1
    this.data.finished = false
    this.data.totalCount = null
    this.setData({
      finished: this.data.finished
    })
    this.getList()
  },
  readFile (e) {
    let index = e.currentTarget.dataset.index
    loading('下载中')
    wx.downloadFile({
      url: this.data.list[index].FilePath,
      success: res => {
        wx.hideLoading()
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath,
          success: r => {
            console.log('打开文档成功')
          }
        })
      },
      fail: e => {
        console.log(e)
        wx.hideLoading()
        wx.showModal({
          title: '对不起',
          content: '文件下载失败，请稍后再试',
          showCancel: false
        })
      }
    })
  },
  onLoad (options) {
    this.data.type = options.type
    this.getList()
  },
  onReady () {},
  onShow () {},
  onHide () {},
  onUnload () {},
  onPullDownRefresh () {},
  onReachBottom () {},
  onShareAppMessage () {}
})